package com.xiaohai.interceptor;

import com.alibaba.fastjson.JSON;
import com.xiaohai.common.R;
import com.xiaohai.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.Objects;

/**
 * ClassName:LoginInterceptor
 * Package:IntelliJ IDEA
 * Description:
 * Author 何诗海
 *
 * @Create 2024/2/23 14:56
 * @Version 1.0
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    // 也可以使用xxxService来查询数据库

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        response.setContentType("text/html;charset=utf-8"); // 解决编码问题(显示的问号)
        String uri = request.getRequestURI();
        log.info("1212:{}", uri);
        if (!StringUtils.hasLength(token)) {
            response.getWriter().write(JSON.toJSONString(R.error("未登录", 401)));
            return false;
        }
        Map<String, Object> verify = JwtUtil.verify(token);
        String account = (String) verify.get("account");
        Map<String, String[]> map = request.getParameterMap();
        String o = map.get("account")[0];
        if (!Objects.equals(o, account)) {
            response.getWriter().write(JSON.toJSONString(R.error("token失效", 501)));
            return false;
        }

        return true;
    }


}
